package com.wang.project.consumer.payment;

import cn.hutool.json.JSONUtil;
import com.wang.project.model.entity.UserInterfacePayment;
import com.wang.project.service.UserInterfacePaymentService;
import com.wang.project.model.modle.MQInerfacePaymentModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 此消费者只是用来保存支付信息，最终支付完成的消息在另外的消费者中
 */
@Service
@Slf4j
@RocketMQMessageListener(
        topic = "payment_addInterfaceNum_topic",
        consumerGroup = "payment-interface-group"
)
public class paymentAddInterfaceNumConsumer implements RocketMQListener<MQInerfacePaymentModel> {

    @Resource
    private UserInterfacePaymentService userInterfacePaymentService;


    /**
     * 保存当前的支付信息 以便之后更新支付结果
     *
     * @param mqInerfacePaymentModel
     */
    @Override
    public void onMessage(MQInerfacePaymentModel mqInerfacePaymentModel) {
        log.info("paymentAddInterfaceNumConsumer success MQInerfacePaymentModel: " + JSONUtil.toJsonStr(mqInerfacePaymentModel));
        List<Long> interfaceIdList = mqInerfacePaymentModel.getInterfaceIdList();
        List<UserInterfacePayment> userInterfacePayments = interfaceIdList.stream().map(item -> {
            UserInterfacePayment userInterfacePayment = new UserInterfacePayment();
            userInterfacePayment.setInterfaceId(item);
            userInterfacePayment.setUserId(mqInerfacePaymentModel.getUserId());
            userInterfacePayment.setAmount(mqInerfacePaymentModel.getAmount());
            userInterfacePayment.setOrderId(mqInerfacePaymentModel.getOrderId());
            userInterfacePayment.setPayStatus(mqInerfacePaymentModel.getPayStatus());
            userInterfacePayment.setSourceScene(mqInerfacePaymentModel.getSourceScene());
            return userInterfacePayment;
        }).collect(Collectors.toList());

        boolean b = userInterfacePaymentService.saveBatch(userInterfacePayments);
        if (!b) {
            log.error("MQ paymentAddInterfaceNumConsumer onMessage 批量保存信息错误，请手动更新支付信息");
        }
        log.info("MQ paymentAddInterfaceNumConsumer onMessage 批量保存信息完成");
    }
}
